#region Copyright Notice

// 
// 
//  
//  Copyright (c) 2009-2011 Anindya Chatterjee
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// 
// 

#endregion

using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace AbstractClass.Extensions
{
    /// <summary>
    /// Provides a set of extension methods for <see cref="Control"/>.
    /// </summary>
    public static class ControlExtensions
    {
        /// <summary>
        /// Gets a set of child controls of type <typeparamref name="T"/> from the <paramref name="parent"/> control.
        /// </summary>
        /// <typeparam name="T">Type of control to find.</typeparam>
        /// <param name="parent">The parent control.</param>
        /// <returns>A list of found child controls of type <typeparamref name="T"/>.</returns>
        public static IEnumerable<T> GetControlsOfType<T>(this Control parent)
        {
            IEnumerable<Control> collection = GetChildControls(parent);
            return collection.OfType<T>();
        }

        /// <summary>
        /// Gets all child controls of the <paramref name="parent"/> control.
        /// </summary>
        /// <param name="parent">The parent control.</param>
        /// <returns>A list of all child controls.</returns>
        public static IEnumerable<Control> GetChildControls(this Control parent)
        {
            var queue = new Queue<Control>();
            queue.Enqueue(parent);

            while (0 < queue.Count)
            {
                Control control = queue.Dequeue();
                if (control == null) continue;
                foreach (Control child in control.Controls)
                {
                    queue.Enqueue(child);
                }
                yield return control;
            }
        }
    }
}